const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
const fs = require('fs')

// 引入mysql连接池
const pool = require("../utils/db.js");

// 查询所有教练
router.get('/coaches', (req, res, next) => {
  let obj = req.query;
  console.log(obj);
  pool.query('select * from coach', [], (err, result) => {
    if (err) {
      return next(err);
    }
    console.log(result);
    res.send({ code: 200, msg: '查询成功', data: result });
  });
})

// 通过id查找教练
router.get('/coachById', (req, res, next) => {
  let obj = req.query;
  console.log(obj);
  pool.query('select * from coach where ?', [obj], (err, result) => {
    if (err) {
      return next(err);
    }
    console.log(result);
    if(result.length===0){
      res.send({code:201,msg:'查询失败'})
    }else{
      res.send({ code: 200, msg: '查询成功', data: result })
    }
  });
})

// 新增教练
router.post('/coach_add', (req, res, next) => {
  let obj = req.body
  pool.query('insert into coach set ?', [obj], (err, result) => {
    if (err) {
      return next(err)
    }
    console.log(result);
    if(result.affectedRows===0){
        res.send({code:201,msg:'新增失败'})
      }else{
        res.send({ code: 200, msg: '新增成功' })
      }
  })
})

// 删除教练
router.post('/coach_delete', (req, res, next) => {
  let obj = req.query
  pool.query('delete from coach where ?', [obj], (err, result) => {
    if (err) {
      return next(err)
    }
    console.log(result);
    if(result.affectedRows===0){
      res.send({code:201,msg:'删除失败'})
    }else{
      res.send({ code: 200, msg: '删除成功' })
    }
  })
})


// 修改教练信息
router.post('/update',(req,res,next)=>{
	//2.1获取传递的数据
	let obj=req.body;
	console.log(obj);
	//2.2执行sql命令
	pool.query("update coach set nickname=?,headpic=?,project=?,introduction=?,achieve=? where coach_id=?",[obj.nickname,obj.headpic,obj.project,obj.introduction,obj.achieve,obj.coach_id],(err,result)=>{
		if(err){
			return next(err);
		}
		console.log(result);
		//结果是对象，如果对象下的属性affectedRows为0说明修改失败
		if(result.affectedRows===0){
			res.send({code:201,msg:'修改失败'});
		}else{
			res.send({code:200,msg:'修改成功',data:result});
		}
	});
})

module.exports = router;